package com.heima.wemedia.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.service.WmSensitiveExcelService;
import com.heima.wemedia.service.WmSensitiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author jay
 * @date 2022/11/17 15:58:53
 */
@Service
public class WmSensitiveExcelServiceImpl implements WmSensitiveExcelService {

    private static final int MAX_LINE_NUM = 1000;

    @Autowired
    private WmSensitiveService wmSensitiveService;


    @Override
    public void downloadAsExcel(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=demo.xlsx");
        try {
            LambdaQueryWrapper<WmSensitive> wrapper = Wrappers.<WmSensitive>lambdaQuery().last("limit " + WmSensitiveExcelServiceImpl.MAX_LINE_NUM);
            List<WmSensitive> list = wmSensitiveService.list(wrapper);
            EasyExcel.write(response.getOutputStream(), WmSensitive.class).sheet().doWrite(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseResult addSensitiveFromExcelFile(MultipartFile file) {
        // 1.参数检测
        if(file == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
        if(!"xlsx".equals(fileType) && !"xls".equals(fileType)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        try {
            EasyExcel.read(file.getInputStream(), WmSensitive.class, new ExcelService(wmSensitiveService)).doReadAll();
        } catch (IOException e) {
            throw new CustomException(AppHttpCodeEnum.EXCEL_READ_FILE_FAILED);
        }


        return ResponseResult.okResult("读取成功");
    }
}
